#!/usr/bin/env python

import optparse
import ConfigParser
import sys
import os

from gfinance_text import *

#this is necessary because both optparse and ConfigParser use raw strings
#used for formatting options - especially in text, but also for html
def stringreplace(s):
  if "[tab]" in s:
    s = s.replace("[tab]", "    ")
  if "[space]" in s:
    s = s.replace("[space]", " ")
  if "[newline]" in s:
    s = s.replace("[newline]", "\n")
  return s

#main is full of idiot code to parse all the command options, declare stuff, and connect the classes.
if __name__ == "__main__":

  #setup commandline variables
  parser = optparse.OptionParser()
  parser.add_option("-c", "--config", dest="configfile",
                    help="""Configuration File - everything can be set here and it is also looked for in ./gfinance.conf, 
                    /etc/gfinance.conf, and /etc/gfinance/gfinance.conf in that order. The command line only supports
                    a limited number of options at this time.""")

  parser.add_option("-v", "--verbose", dest="verbose", default=False,
                    action="store_true", help="Verbose output")

  parser.add_option("-u", "--username", help="Username")
  parser.add_option("-p", "--password", help="Password")
  parser.add_option("-m", "--mode", help="[TEXT|HTML|QT] default is TEXT")
  parser.add_option("--noperformance", action="store_false", default=False, help="Do not include Performance Information - default False")
  parser.add_option("--transactioninfo", action="store_true", default=False, help="Include Transaction Information - default False")
  parser.add_option("--portfolioNum", dest="NUM", help="Google Portfolio Number - default is 1")

  #the following are specific to modes - errors will be handled manually
  parser.add_option("--fieldDelim", dest="fdelim", help="Field delimeter")
  parser.add_option("--transactionDelim", dest="tdelim", help="Transaction delimeter")
  parser.add_option("--stockDelim", dest="sdelim", help="Stock delimeter")

  (options, args) = parser.parse_args()

  print options
 
  #try to find a configfile, if it exists 
  configfile = options.configfile
  if not configfile:
    if os.path.exists("./gfinanceview.conf"):
      configfile = "./gfinanceview.conf"
    elif os.path.exists("/etc/gfinanceview.conf"):
      configfile = "/etc/gfinanceview.conf"
    elif os.path.exists("/etc/gfinanceview/gfinanceview.conf"):
      configfile = "/etc/gfinanceview/gfinanceview.conf"
    elif options.verbose:
      print "Configuration File not found, continuing anyway..."

  #setup configuration file variables
  if configfile:
    config = ConfigParser.ConfigParser()
    config.read(configfile)

  #get username
  if options.username:
    username = options.username
  else:
    try:   
      username = config.get("DEFAULT", "username")
    except:
      print """ERROR: Program could not determine the username
       Specify a configfile or use the -u option"""
      raise
 
  #get password
  if options.password:
    password = options.password
  else:
    try:
      password = config.get("DEFAULT", "password")
    except:
      print """ERROR: Program could not determine the password
       Specify a configfile or use the -p option"""
      raise

  #get mode
  if options.mode:
    mode = options.mode
  else:
    try:
      mode = config.get("DEFAULT", "mode")
    except:
      mode = "TEXT"
  
  #get performanceInfo - if not specified it defaults to true
  if options.noperformance != None and options.noperformance == "False":
    performance = False
  else: 
    try:
      performance = config.get("DEFAULT", "performanceinfo")
    except (NameError, ConfigParser.NoOptionError):
      if options.verbose:
        print "Performance Configuration Information not found... setting performanceinfo=True"
      performance = True

  #get transactionlist - if not specified it defaults to nothing
  if options.transactioninfo != None and options.transactioninfo == "False":
    transactionlist = []
  elif options.transactioninfo != None and options.transactioninfo == "True":
    transactionlist = ["companyName","date","pricePerShare","numShares","commission"]
    if options.verbose:
      print "transactioninfo sets all transactioninfo to print"
      print "for more fined grain control use the config file"
  else: 
    try:
      transactionlist = config.get("DEFAULT", "transactionlist").split(",")
    except (NameError, ConfigParser.NoOptionError):
      if options.verbose:
        print "Transaction Configuration Information not found... setting transactioninfo=None"
      transactionlist = []
  #check that transactionlist contains only valid stuff
  for i in transactionlist:
    if i != "companyName" and i != "date" and i != "pricePerShare" and i != "numShares" and \
        i != "commission" and i != "transaction":
      print "ERROR: invalid value in transactioninfo"
      print "valid args are comma seperated and are one of the following:"
      print "companyName,date,pricePerShare,numShares,commission"
      sys.exit(-1)


  #get portfolio number - if not specified default to 1
  if options.NUM:
    portfolioNumber = options.NUM
  else:
    try:
      portfolioNumber = config.get("DEFAULT", "portfolionum")
    except:
      if options.verbose:
        print "Portfolio Number not found... setting portfolioNumber=1"
      portfolioNumber = 1

  #get fieldlist - keep in mind

  #########################################
  #Done Generic Fetching Options
  #########################################
  
  #text based stock stuff
  if mode == "TEXT":

    #get *text* field delimeter
    if options.fdelim:
      fdelim = options.fdelim
    else:
      try:
        fdelim = config.get("text", "fielddelim")
      except:
        if options.verbose:
          print "field delimeter not found... setting fielddelim=\t\t"
        fdelim = "\t\t"

    fdelim = stringreplace(fdelim)

    #get *text* stock delimeter
    if options.sdelim:
      sdelim = options.sdelim
    else:
      try:
        sdelim = config.get("text", "stockdelim")
      except:
        if options.verbose:
          print "stock delimeter not found... setting stockdelim=\n\n"
        sdelim = "\n"
    sdelim = stringreplace(sdelim)

    #get transaction delimiter
    if options.tdelim:
      tdelim = options.tdelim
    else:
      try:
        tdelim = config.get("text", "transactiondelim")
      except:
        if options.verbose:
          print "stock delimeter not found... setting stockdelim=\n\n"
        tdelim = "\n"

    tdelim = stringreplace(tdelim)
    textportfolio = text_portfolio(username, password, portfolioNumber, fdelim, sdelim, tdelim, transactionlist)
    
